//
//  DAAlertView.m
//  DAAlertViewFour
//
//  Created by DreamArts on 16/4/8.
//  Copyright © 2016年 lidongyang. All rights reserved.
//

#import "DAAlertView.h"

@interface DAAlertView ()
@property (nonatomic,strong) UIWindow *overlayWindow;    // 获取的window
@property (nonatomic,strong) UIView *buttonsView;       // 整个button 所在的view
@property (nonatomic) UIView *backgroundView;          // 用来遮盖的 view
@property (nonatomic,strong) NSMutableArray *innerButtonsList;   // 存放button 的数组
@property (nonatomic) CGFloat titleHeight;           // title Label的高度
@property (nonatomic) CGFloat contentHeight;  // 内容label 的高度
@property (nonatomic) CGFloat buttonsListHeight;  //button 数组里所有button 的总高度
@end
@implementation DAAlertView

#pragma mark - 初始化
- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        // TODO 做一些默认的设置
        [self contentType];
    }
    return self;
}
#pragma mark - 内容类型的设置
- (void)contentType {
    switch (self.alertDisplayerContentType) {
        case DAAertDisplayerContentTypeDefault:  // 默认样式
            [self defautlSet];
            break;
        default:
            [self defautlSet];
            break;
    }
}
#pragma mark -默认类型的情况下
- (void)defautlSet {
    self.alertViewWidth = 250;  // 默认alertView 的宽
    self.buttonHeight = 45;     // 默认button的高
    self.buttonsInset = 0.5f;   // 每个button 之间的距离
    // 默认title 距离父视图 距离上15 左边 10 下 0 右10
    self.titleEdgeInsets = UIEdgeInsetsMake(15, 10, 0, 10);
    // 默认content 距离父视图 上0 左10 下0 右 10
    self.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 10);
    // 默认是不隐藏取消的按钮
    self.isHiddenCancelButton = NO;
    // 默认点击其他地方 关闭alert的效果是开启的
    self.isHiddenDisplayerByTouch = YES;
    self.otherButtonTitleColor = [UIColor colorWithRed:241.0 / 255.0
                                                 green:67.0 / 255.0
                                                  blue:67.0 / 255.0 alpha:1.0f];
    self.alertDisplayerShowType = DAAlertDisplayerShowTypeBounce;
    self.alertDisplayerPositionType = DAAlertDisplayerPositionTypeCenter;
    /*
     创建思路: 最底层是self self的上层是alertView 
              标题 内容 和所有button的view 都在alertView上
     */
    // alertView
    self.alertView = [[UIView alloc] init];
    self.alertView.backgroundColor = [UIColor whiteColor];
    self.alertView.clipsToBounds = YES;
    // button 所在的view
    self.buttonsView = [[UIView alloc] init];
    self.buttonsView.backgroundColor = [UIColor colorWithWhite:0.8f alpha:1.0f];
    self.buttonsView.userInteractionEnabled = YES;
    // 标题
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.font = [UIFont systemFontOfSize:15];
    self.titleLabel.textColor = [[UIColor blackColor] colorWithAlphaComponent:0.9f];
    self.titleLabel.numberOfLines = 0;
    self.titleLabel.lineBreakMode = NSLineBreakByCharWrapping;
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    // 内容的label
    self.contentLabel = [[UILabel alloc] init];
    self.contentLabel.font = [UIFont systemFontOfSize:15];
    self.contentLabel.textColor = [[UIColor blackColor] colorWithAlphaComponent:0.7f];
    self.contentLabel.numberOfLines = 0;
    self.contentLabel.lineBreakMode = NSLineBreakByCharWrapping;
    self.contentLabel.textAlignment = NSTextAlignmentCenter;
    // 取消按钮
    self.cancelButton = [[UIButton alloc] init];
    [self.cancelButton setTitle:@"取消" forState:0];
    [self.cancelButton setTitleColor:[UIColor colorWithRed:27.0 / 255.0
                                                     green:166.0 / 255.0
                                                      blue:201.0 / 255.0
                                                     alpha:1.0f] forState:0];
    /** 取消按钮的tag  */
    self.cancelButton.tag = 999;
    self.cancelButton.titleLabel.font = [UIFont systemFontOfSize:15];
    self.cancelButton.backgroundColor = [UIColor whiteColor];
    [self.cancelButton addTarget:self action:@selector(displayerButtonAction:)
                forControlEvents:UIControlEventTouchUpInside];

}
#pragma mark -类方法创建alert
///类方法
+ (void)showDAAlertWithPositionType:(DAAlertDisplayerPositionType)positionType
                      animationType:(DAAlertDisplayerShowType)animationType
                            titleText:(NSString *)title
                          contentText:(NSString *)content
                    cancelButtonTitle:(NSString *)cancelButtonTitle
                           buttonList:(NSArray *)buttons
                    handleActionBlock:(displayerActionBlock)block {
    
    DAAlertView *alert = [[DAAlertView alloc] init];
    alert.alertDisplayerPositionType = positionType;
    alert.titleLabel.text = title;
    alert.contentLabel.text = content;
    alert.otherButtonList = buttons;
    alert.displayerActionBlock = block;
    alert.alertDisplayerShowType = animationType;
    // 如果取消按钮的title 是空的 就开启点击屏幕其他地方让alert消失
    if (cancelButtonTitle == nil || cancelButtonTitle.length == 0) {
        alert.isHiddenCancelButton = YES;
        alert.isHiddenDisplayerByTouch = YES;
    }
    else{
        [alert.cancelButton setTitle:cancelButtonTitle forState:UIControlStateNormal];
    }
    [alert displayerShow];
}
#pragma mark - 创建其他的方法
-(void)displayerShow {
    [self creatAlert];       // 创建alert
    [self computeTop];       // 计算title的frame 并添加到 alertView
    [self computeContent];   // 计算content的frame 并天骄到 alertView
    [self computeButtons];   // 计算button的frame 并添加到 alertView
    [self showAnimation];    // 调用动画效果
}
#pragma mark -根据位置类型 创建alert
- (void)creatAlert {
    self.titleHeight = 0;
    self.contentHeight = 0;
    self.buttonsListHeight = 0;
    self.innerButtonsList = nil;
    // 调用内部创建button的方法 根据拿到的button数组
    [self innerButtonsList];
    [self.overlayWindow addSubview:self];
    self.frame = self.overlayWindow.bounds;
    [self addSubview:self.backgroundView];
    [self addSubview:self.alertView];
    self.alertView.transform = CGAffineTransformIdentity;
    self.alertView.alpha = 1.0f;
    switch (self.alertDisplayerPositionType) {
        case DAAlertDisplayerPositionTypeCenter:{
            if (self.alertView.layer.cornerRadius == 0.0f) { //设置圆角
                self.alertView.layer.cornerRadius = 8.0f;
            }
        }
            break;
        case DAAlertDisplayerPositionTypeBottom:{
            self.alertView.layer.cornerRadius = 0.0f;
            self.alertViewWidth = [UIScreen mainScreen].bounds.size.width;
        }
            break;
        default:
            break;
    }
}
#pragma mark - 根据传入的数组 进行创建button
- (NSMutableArray *)innerButtonsList {
    if (!_innerButtonsList) {
        self.innerButtonsList = [NSMutableArray array];
        if (self.otherButtonList && self.otherButtonList.count > 0) {
            // 遍历数组
            [self.otherButtonList enumerateObjectsUsingBlock:^(id obj,
                                                               NSUInteger idx,
                                                               BOOL * stop) {
                // 根据传入的button 数组里元素的类型 创建button
                // 当传入的是字符串的情况下
                if ([obj isKindOfClass:[NSString class]]) {
                    UIButton *button = [self customButton];
                    [button setTitle:obj forState:0];
                    [self.innerButtonsList addObject:button];
                }
                // 当传入的对象就是button 的情况下
                else if ([obj isKindOfClass:[UIButton class]]){
                    [self.innerButtonsList addObject:obj];
                }
            }];
        }
        // 遍历数组 给每个button 添加点击方法
        [self.innerButtonsList enumerateObjectsUsingBlock:^(UIButton *obj,
                                                            NSUInteger idx,
                                                            BOOL * stop) {
            [obj setTag:idx];
            [obj addTarget:self action:@selector(displayerButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        }];
        // 判断当前的取消按钮 是不是隐藏
        if (!self.isHiddenCancelButton) {
            // 当button数组的个数等于1 并且 显示的类型不是在视图的下方的话
            if (self.otherButtonList.count == 1 && self.alertDisplayerPositionType != DAAlertDisplayerPositionTypeBottom) {
                // 就把取消按钮插入到button数组里的第一位
                // 也就是说button 数据里 只有一个button 就是插入的取消按钮
                [self.innerButtonsList insertObject:self.cancelButton atIndex:0];
            }
            else{
                [self.innerButtonsList addObject:self.cancelButton];
            }
        }
    }
    return _innerButtonsList;
}
#pragma mark - 计算出title 的frame 并添加到alertView
- (void)computeTop {
    if (self.titleLabel && self.titleLabel.text != nil && self.titleLabel.text.length > 0) {
        CGFloat titleWidth = self.alertViewWidth - self.titleEdgeInsets.left - self.titleEdgeInsets.right;
        CGFloat titleHeight = [self.titleLabel sizeThatFits:CGSizeMake(titleWidth, MAXFLOAT)].height;
        self.titleLabel.frame = CGRectMake(self.titleEdgeInsets.left,
                                           self.titleEdgeInsets.top,
                                           titleWidth,
                                          titleHeight);
        [self.alertView addSubview:self.titleLabel];
        self.titleHeight = titleHeight + self.titleEdgeInsets.top + self.titleEdgeInsets.bottom;
    }
}
#pragma mark - 计算出content 的frame 并添加到alertView
- (void)computeContent {
    switch (self.alertDisplayerContentType) {
        case DAAertDisplayerContentTypeDefault:{
            if (self.contentLabel && self.contentLabel.text != nil && self.contentLabel.text.length > 0) {
                CGFloat textW = self.alertViewWidth - self.contentEdgeInsets.left - self.contentEdgeInsets.right;
                CGFloat textH = [self.contentLabel sizeThatFits:CGSizeMake(textW, MAXFLOAT)].height;
                //设定一个内容控件最小高度
                textH = textH < 50 ? 50 : textH;
                self.contentLabel.frame = CGRectMake(self.contentEdgeInsets.left,
                                              self.contentEdgeInsets.top + self.titleHeight,
                                              textW,
                                              textH);
                [self.alertView addSubview:self.contentLabel];
                self.contentHeight = self.contentEdgeInsets.top + textH + self.contentEdgeInsets.bottom;
            }
        }
            break;
        default:
            break;
    }
}
#pragma mark - 计算出button 的frame 并添加到alertView
- (void)computeButtons {
    self.buttonsListHeight = self.buttonsInset;
    [self.innerButtonsList enumerateObjectsUsingBlock:^(UIButton *obj,
                                                    NSUInteger idx,
                                                    BOOL * stop) {
            //根据显示类型进行按钮排列
        switch (self.alertDisplayerPositionType) {
                // 当alert在视图中间显示的情况下
            case DAAlertDisplayerPositionTypeCenter:{
                // 只有一个按钮的情况下
                if (self.innerButtonsList.count == 1) {
                    obj.frame = CGRectMake(0,
                                           self.buttonsListHeight,
                                           self.alertViewWidth,
                                           self.buttonHeight);
                    self.buttonsListHeight = self.buttonHeight + self.buttonsInset;
                }
                // 有两个按钮的情况下
                else if (self.innerButtonsList.count == 2) {
                    obj.frame = CGRectMake(idx == 0 ? 0 : self.alertViewWidth / 2 + 0.5f,
                                           self.buttonsListHeight,
                                           self.alertViewWidth / 2,
                                           self.buttonHeight);
                    if (idx == 1) {
                        self.buttonsListHeight = self.buttonHeight + self.buttonsInset;
                    }
                }
                // 有多个按钮的情况下
                else{
                    obj.frame = CGRectMake(0,
                                           self.buttonsListHeight,
                                           self.alertViewWidth,
                                           self.buttonHeight);
                    self.buttonsListHeight += self.buttonHeight + self.buttonsInset;
                }
            }
                break;
                // 当alert 在视图底部显示的情况下
            case DAAlertDisplayerPositionTypeBottom:{
                obj.frame = CGRectMake(0,
                                       self.buttonsListHeight,
                                       self.alertViewWidth,
                                       self.buttonHeight);
                self.buttonsListHeight += self.buttonHeight + self.buttonsInset;
            }
                break;
            default:
                break;
        }
        if (idx == self.innerButtonsList.count - 1) {
            self.buttonsListHeight -= self.buttonsInset;
        }
        [self.buttonsView addSubview:obj];
    }];
    //设置ButtonsView的尺寸
    if (self.innerButtonsList.count > 0) {
        self.buttonsView.frame = CGRectMake(0,
                                        self.titleHeight + self.contentHeight,
                                        self.alertViewWidth,
                                        self.buttonsListHeight);
        [self.alertView addSubview:self.buttonsView];
    }
    else{
        self.buttonsListHeight = 0;
    }
}
#pragma mark - 每个button 的点击方法
- (void)displayerButtonAction:(UIButton *)sender {
    if (self.displayerActionBlock && sender.tag != 999) {
        self.displayerActionBlock(self,sender.tag);
    }
    if (sender.tag == 999) {
        self.displayerActionBlock(self, sender.tag);
    }
    // 消失
    [self displayerHidden];
    
    
}
#pragma mark - alert弹出的动画效果
- (void)showAnimation {
    CGFloat totalH = self.titleHeight + self.contentHeight + self.buttonsListHeight;
    // 判断alert显示的位置
    switch (self.alertDisplayerPositionType) {
            // 如果是在视图中间的话
        case DAAlertDisplayerPositionTypeCenter:{
            // 计算出它显示的frame
            self.alertView.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width - self.alertViewWidth) / 2,([UIScreen mainScreen].bounds.size.height - totalH) / 2,
                self.alertViewWidth, totalH);
        }
            break;
            // 如果在视图的底部的情况下
        case DAAlertDisplayerPositionTypeBottom:{
            // 计算出它显示的frame
            self.alertView.frame = CGRectMake(0,[UIScreen mainScreen].bounds.size.height - totalH,
                                              self.alertViewWidth,totalH);
        }
            break;
        default:
            break;
    }
    [self.overlayWindow makeKeyAndVisible];
    /*
     注意: 下面是两层switch  思路 首先判断的是 当前alert显示的类型 再判断动画的样式
     */
    // 第一层 1.switch 先判断alert的位置类型
    switch (self.alertDisplayerPositionType) {
            // 1.1当alert在视图中间显示的情况下
        case DAAlertDisplayerPositionTypeCenter:{
            // 第二层 2.switch 再判断 动画展示的类型
            switch (self.alertDisplayerShowType) {
                    // 2.1 alert 展示的动画效果 1
                case DAAlertDisplayerShowTypeBounce:{
                    self.alertView.transform = CGAffineTransformMakeScale(1.0f, 1.0f);
                    self.alertView.alpha = 0.0f;
                    [UIView animateWithDuration:0.1f animations:^{
                        self.alertView.transform = CGAffineTransformMakeScale(1.1f, 1.1f);
                        self.alertView.alpha = 1.0f;
                    } completion:^(BOOL finished) {
                        [UIView animateWithDuration:0.1f animations:^{
                            self.alertView.transform = CGAffineTransformMakeScale(1.0f, 1.0f);
                        } completion:^(BOOL finished) {
//                            [UIView animateWithDuration:0.2f animations:^{
//                                self.alertView.transform = CGAffineTransformMakeScale(1.0f, 1.0f);
//                            } completion:nil];
                        }];
                    }];
                }
                    break;
                    // 2.2 alert展示的动画效果 2
                case DAAlertDisplayerShowTypeDrawer:{
                    self.alertView.alpha = 0.0f;
                    self.alertView.transform = CGAffineTransformMakeTranslation(0, 50);
                    [UIView animateWithDuration:0.2f animations:^{
                        self.alertView.transform = CGAffineTransformMakeTranslation(0, 0);
                        self.alertView.alpha = 1.0f;
                    } completion:nil];
                }
                    break;
                    
                default:
                    break;
            }
        }
            break;
            // 1.2 alert在底部视图显示的情况下
        case DAAlertDisplayerPositionTypeBottom:{
            self.alertView.transform = CGAffineTransformMakeTranslation(0, self.alertView.frame.size.height);
            [UIView animateWithDuration:0.2f animations:^{
                self.alertView.transform = CGAffineTransformMakeTranslation(0, 0);
            } completion:nil];
        }
        default:
            break;
    }
}
#pragma mark - alert消失
- (void)displayerHidden {
    // 动画开始
    [UIView animateWithDuration:0.15f
                     animations:^{
                         // 判断 alert在视图上显示的类型
                         switch (self.alertDisplayerPositionType) {
                             case DAAlertDisplayerPositionTypeCenter:{
                                 self.alertView.transform = CGAffineTransformMakeScale(1.2f, 1.2f);
                                 self.alertView.alpha = 0.0f;
                             }
                                 break;
                             case DAAlertDisplayerPositionTypeBottom:{
                                 self.alertView.transform = CGAffineTransformMakeTranslation(0, self.alertView.frame.size.height);
                             }
                                 break;
                             default:
                                 break;
                         }
                         self.backgroundView.alpha = 0.0f;
                     } completion:^(BOOL finished) {
                         // 动画结束的时候
                         self.overlayWindow = nil;
                         [self.alertView removeFromSuperview];
                         [self.window removeFromSuperview];
                         self.alertView = nil;
                         [self.backgroundView removeFromSuperview];
                         self.backgroundView = nil;
                         [self removeFromSuperview];
                         [[UIApplication sharedApplication].windows enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(UIWindow *window, NSUInteger idx, BOOL *stop) {
                             if ([window isKindOfClass:[UIWindow class]] && window.windowLevel == UIWindowLevelNormal && ![[window class] isEqual:[DAAlertView class]]) {
                                 [window makeKeyWindow];
                                 *stop = YES;
                             }
                         }];
                     }];
    
}
#pragma mark - 点击屏幕触发的方法
- (void)singleTap {
    if (self.isHiddenDisplayerByTouch) {
        [self displayerHidden];
    }
}
-(UIWindow *)overlayWindow{
    if (!_overlayWindow) {
        _overlayWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        _overlayWindow.backgroundColor = [UIColor clearColor];
        _overlayWindow.windowLevel = UIWindowLevelAlert;
        _overlayWindow.userInteractionEnabled = YES;
    }
    return _overlayWindow;
}

-(UIView *)backgroundView{
    if (!_backgroundView) {
        _backgroundView = [[UIView alloc] initWithFrame:self.bounds];
        _backgroundView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3f];
        _backgroundView.userInteractionEnabled = YES;
        _backgroundView.alpha = 1.0f;
        
        UITapGestureRecognizer *singleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap)];
        [_backgroundView addGestureRecognizer:singleTapGesture];
    }
    return _backgroundView;
}
#pragma mark -创建button 按钮
-(UIButton *)customButton{
    UIButton *button = [[UIButton alloc] init];
    [button setTitleColor:_otherButtonTitleColor forState:0];
    button.titleLabel.font = [UIFont systemFontOfSize:15];
    button.backgroundColor = [UIColor whiteColor];
    return button;
}


+ (void)delayDisplayer{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        DAAlertView *alert = [[DAAlertView alloc]init];
        [alert displayerHidden];
        
    });
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
